package com.controller;

import com.constant.Constant;
import com.dao.GoldPointMapper;
import com.entity.GoldPoints;
import com.entity.Resource;
import com.entity.User;
import com.service.GoldPointService;
import com.service.ResourceService;
import com.service.UserGpService;
import com.util.AjaxResult;
import com.util.StringUtil;
import com.vo.GoldPointsVo;
import com.vo.ResourceVo;
import com.vo.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import com.constant.Constant;
import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.service.impl.ResourceServiceImpl;
import com.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import sun.text.resources.FormatData;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/resource")
public class ResourceCtl {
    //    潘军 前台查询当前用户上传的资源
//    后台查询资源
    @Autowired
    ResourceService resourceService;
    @Autowired
    UserGpService gpService;
    @Autowired
    GoldPointService goldPointService;

    //pj 删除资源
    @RequestMapping("/removeFrontResource.do")
    @ResponseBody
    public AjaxResult removeFrontResource(String id) {
        int i = StringUtil.getInt(id);
        AjaxResult result = resourceService.removeFrontResource(i);
        return result;

    }

    @RequestMapping("/findBackResource.do")
    public AjaxResult findBackResource(HttpServletRequest request, @RequestParam("pageNo") String pageNo, ResourceVo resourceVo) {
        AjaxResult result = new AjaxResult(true, "", null);
        int pageno = StringUtil.getInt(pageNo);
        if (resourceVo.getUser_name() == null) {
            User user = (User) request.getSession().getAttribute(Constant.SESSION_USER);
            resourceVo.setUser_id(user.getId());
        } else {

        }
        PageInfo<Resource> backResource = resourceService.findBackResource(pageno, resourceVo);
        result.setObj(backResource);
        return result;
//        else if(rs.getUser_name()!=""){
//            int uid = userService.findUidByName(rs.getUser_name());
//            rs.setUser_id(uid);
    }

    //    播放资源 pj
    @RequestMapping("/play.do")
    public String play(HttpServletRequest request, @RequestParam("path") String path) {
        request.getSession().setAttribute("path", path);
        return "/background/back_resourceDetailSet";
    }

    //    下载资源 pj
//    @RequestMapping("/down.do")
//    public void down(HttpServletRequest request, @RequestParam("resourceId")Integer resourceId)  {
//        request.getSession().setAttribute("path",path);
//        return "/background/back_resourceDetailSet";
//    }
    //后台资源非MP4类型文件实现下载功能
    @RequestMapping("/down.do")
    public ResponseEntity<byte[]> down(HttpServletRequest request, Integer resourceId) throws Exception {
        Resource res = resourceService.findResourceByid(resourceId);
        ServletContext context = request.getSession().getServletContext();
        String path = request.getSession().getServletContext().getRealPath("/" + res.getPath());
        //要进行下载，就需要对这个目录的文件 返回一个输入流
        FileInputStream is = new FileInputStream(path);
        byte[] bytes = new byte[is.available()];
        //对文件进行读的操作  bytes数组里现在就是这个文件的二进制数据
        is.read(bytes);

        HttpHeaders headers = new HttpHeaders();
        // 参数一:表示当前所使用的MIME协议方式,即下载的方式
        // 其值有两种
        //  1.attachment:以附件的方式进行下载
        //  2.inline:在线打开
        // 参数二:下载时所显示的文件名
        headers.setContentDispositionFormData("attachment", res.getOriginal_name());

        //第一个参数：响应内容：文件的数据读到二进制数组里
        //第二个参数是响应头：浏览器解析内容需要的一些数据
        //第三个参数是响应编码：
        ResponseEntity entity = new ResponseEntity(bytes, headers, HttpStatus.OK);

        return entity;
    }


    //    启用禁用资源 pj
    @RequestMapping("/toggleStatus.do")
    @ResponseBody
    public AjaxResult toggleStatus(Resource resource) {
        AjaxResult result = resourceService.toggleStatus(resource);
        return result;

    }

    //    潘军  添加资源
//    @RequestMapping("/addFrontResource.do")
//    @ResponseBody
//    public AjaxResult addFrontResource(HttpServletRequest request, FormatData formatData){
//        AjaxResult result=new AjaxResult(true,"添加资源成功",null);
//        Constant c= (Constant) request.getSession().getAttribute("constant");
//        User user=c.user;
//        resourceService.addFrontResource(formatData,user);
//                return null;
//
//    }


    ////@李奇洲
    @RequestMapping("/checkup.do")
    @ResponseBody
    public AjaxResult checkup(@RequestParam("resource_id") Integer resourceId, HttpSession session) {
        System.out.println("checkup方法执行了，传入的ResourceId是=" + resourceId);
        //根据resourceId查询Resource
        Resource resource = resourceService.selectResourceByResourceId(resourceId);
        System.out.println("封装好的Resource对象是=" + resource);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setObj(resource);
        //获取Session中的User对象
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        System.out.println("Session中的User对象=" + user);
        //作者的ID
        Integer authorId = resource.getUser_id();
        //用户的id
        Integer userid = user.getId();

        //用户的积分金币总合的对象
        GoldPointsVo userGoldPointsVo = gpService.findGoldPointsVoByUid(userid);
        //资源需要的积分或金币
        Integer cost_number = resource.getCost_number();
        //用户目前拥有的积分
        Integer user_sum_point_count = userGoldPointsVo.getSum_point_count();
        //用户目前拥有的金币
        Integer user_sum_gold_count = userGoldPointsVo.getSum_gold_count();
        //积分对象，用于增加扣除积分金币记录
        GoldPoints author_GoldPoints = new GoldPoints(authorId, "售出课程收入积分", new Date());
        GoldPoints user_GoldPoints = new GoldPoints(userid, "购买资源扣除积分", new Date());
        //查询用户购买记录
        UserResource userResource = resourceService.selectUserResourceByUidAndResId(userid, resourceId);
        //userResource==null  用户没有购买过课程
        if (userResource == null) {
            resourceService.insertUserResource(new UserResource(userid, resourceId, new Date(), new Date()));
            //判断资源是金币还是积分 0积分，1金币
            //如果是积分
            if (resource.getCost_type() == 0) {
                //判断用户积分是否足够
                if (user_sum_point_count >= cost_number) {
                    user_GoldPoints.setPoint_count(0 - cost_number);//扣除的相应积分
                    user_GoldPoints.setGold_count(0);//金币
                    // System.out.println("ddddddddddd"+user_GoldPoints);
                    ajaxResult.setMsg("你的积分足够");
                    int i = goldPointService.insertPointGoldCount(user_GoldPoints);
                    System.out.println("扣除用户积分成功，接下来给作者增加积分");
                    author_GoldPoints.setPoint_count(cost_number);//增加相应积分
                    author_GoldPoints.setGold_count(0);//金币
                    int i1 = goldPointService.insertPointGoldCount(author_GoldPoints);
                    System.out.println("给作者增加积分=" + i1);
                    ajaxResult.setSuccess(true);
                } else {
                    ajaxResult.setSuccess(false);
                    ajaxResult.setMsg("用户的积分不足够");
                }
            } else {
                //如果资源需要使用金币购买
                if (user_sum_gold_count >= cost_number) {
                    user_GoldPoints.setPoint_count(0);//积分
                    user_GoldPoints.setGold_count(0 - cost_number);//扣除的相应金币
                    user_GoldPoints.setInfo("购买资源扣除金币");
                    int i = goldPointService.insertPointGoldCount(user_GoldPoints);
                    //给作者增加金币
                    author_GoldPoints.setPoint_count(0);//积分
                    author_GoldPoints.setGold_count(0 - cost_number);//给作者增加金币
                    author_GoldPoints.setInfo("售出课程收入积分");
                    int i1 = goldPointService.insertPointGoldCount(author_GoldPoints);
                    ajaxResult.setSuccess(true);
                } else {
                    ajaxResult.setSuccess(false);
                    ajaxResult.setMsg("用户的金币不足够");
                }
            }
        } else {
            ajaxResult.setSuccess(true);
            ajaxResult.setMsg("您已经购买过该课程");
        }
        return ajaxResult;
    }

    //根据Resoource id查询Resource @李奇洲
    @RequestMapping("/showRs.do")
    //@RequestParam("course_id")Integer courseId,
    // String path
    public String showRs(@RequestParam("resource_id") Integer resourceId, HttpSession session) {
        System.out.println("showRs方法执行了,传入的，course_id="
                + "resource_id=" + resourceId);
        Resource resource = resourceService.selectResourceByResourceId(resourceId);
        session.setAttribute("resource", resource);
        return "front/front_courseDetail";
    }


}
